package com.tools.cleanmaster.model.item;

import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.TrashUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by liyunfeng on 15/12/2.
 */
public class RegularUtils {
    private final static String TAG = "RegularUtils";
    /**
     * get the file size and count
     *
     * @param file is a directoryFile
     */
    public static void getRegularTrash(File file, RegularTrashData rtd) {
        long[] countAndSize = TrashUtils.getFileCountAndSizeWithDepth(file, 10);
        rtd.count += countAndSize[0];
        rtd.size += countAndSize[1];
    }

    /**
     * 正则匹配字符串
     * @param strSrc 需要匹配的字符串
     * @param regular 正则表达式
     * @return true：匹配成功；false：匹配失败
     */
    private static boolean matchRegular(String strSrc,String regular){
        Pattern subPathRegexPattern = null;
        try {
            subPathRegexPattern = Pattern.compile(regular);
        }
        catch (PatternSyntaxException e) {
            subPathRegexPattern = null;
        }
        if (null == subPathRegexPattern) {
            throw new IllegalArgumentException("z.m:\"" + regular + "\".");
        }

        Matcher matcher = subPathRegexPattern.matcher(strSrc);
        return null != matcher && matcher.matches();
    }
    /**
     * 目录名 匹配本级的所有正则式子
     * @param strDirName 目录名
     * @param needMatchMap map的key需要匹配的本级正则式子，value是所对应完整正则式子list。
     * @return 返回匹配的完整正则表达式的list。
     */
    private static List<RegularTrashData> matchRegurarDirName(String strDirName,Map<String,List<RegularTrashData>> needMatchMap){
        List<RegularTrashData> regularList = new ArrayList<RegularTrashData>();
        for(Map.Entry<String, List<RegularTrashData>> item :needMatchMap.entrySet()){
            String key = item.getKey();
            List<RegularTrashData> value = item.getValue();
            if(matchRegular(strDirName,key)){
                regularList.addAll(value);
            }
        }
        return regularList;
    }
    /**
     * 递归处理 文件所对应的正则list
     * @param parentFile 处理的目录的文件对象
     * @param regularTrashs 正则数据list
     * @param deep 固定目录下递归的级数。0:表示再递归处理固定路径
     */
    public static void matchRegularList(File parentFile,List<RegularTrashData> regularTrashs,int deep){
        if (FeatureConfig.DEBUG_LOG) {
            String strRegular = "";
            for(RegularTrashData regular : regularTrashs){
                strRegular+=(";"+regular.regularTrashBean.regulars);
            }
            LogHelper.v(TAG,
                    "regular_cache deal parentPath=" + parentFile.getAbsolutePath() + ";strRegular=" + strRegular);
        }
        //key 正则式子子目录 value 正则RegularTrashData list。
        Map<String,List<RegularTrashData>> needMatchMap = new HashMap<String, List<RegularTrashData>>();
        for(RegularTrashData regularItem :regularTrashs){
            if(null == regularItem.regularArray){
                //通过分隔符得到 正则数组。
                String strRegular = null;
                if(regularItem.regularTrashBean.regulars.startsWith("/")){
                    strRegular = regularItem.regularTrashBean.regulars.substring(1);
                }else{
                    strRegular = regularItem.regularTrashBean.regulars;
                }
                regularItem.regularArray = strRegular.split("/");
            }
            if(regularItem.regularArray.length <= deep){
                //检出出结果
                regularItem.trashFilePaths.add(parentFile.getAbsolutePath());
                if (FeatureConfig.DEBUG_LOG) {
                    LogHelper.v(TAG, "regular_cache find item:"+parentFile.getAbsolutePath()
                            +";count="+regularItem.count
                            +";size="+regularItem.size);
                }
                continue;
            }
            String strRegularItem = regularItem.regularArray[deep];
            List<RegularTrashData> regularList = null;
            if(needMatchMap.containsKey(strRegularItem)){
                regularList = needMatchMap.get(strRegularItem);
            }else{
                regularList = new ArrayList<RegularTrashData>();
                needMatchMap.put(strRegularItem,regularList);
            }
            regularList.add(regularItem);
        }
        //得到子目录名称数组
        String[] allSubPath = TrashUtils.listDir(parentFile);
        if (null == allSubPath || 0 == allSubPath.length) {
            return;
        }
        //循环目录数组，得到目录满足的正则表达式。
        for(int i = 0; i< allSubPath.length; i++){
            String subDirName = allSubPath[i];
            List<RegularTrashData> regularList = matchRegurarDirName(subDirName,needMatchMap);
            if(!regularList.isEmpty()){
                matchRegularList(new File(parentFile,subDirName),regularList,deep+1);
            }
        }
    }
}
